<!--认证-->
<script setup>
import { ref } from 'vue';
import { message } from 'ant-design-vue';
import axios from 'axios';
import {useRouter} from "vue-router";
const  router = useRouter();
// 表单数据
const formData = ref({
  name: '',
  idCard: '',
  agreement: false
});

// 存储文件和预览 URL
const files = ref([]);
const fileUrls = ref([]);

// 处理文件上传
const handleImageUpload = (event) => {
  const uploadFiles = event.target.files;

  if (uploadFiles.length + files.value.length >= 2) {
    message.error('最多只能上传1张图片');
    return;
  }

  for (const file of Array.from(uploadFiles)) {
    if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
      message.error('只支持 jpg、png、gif 格式的图片');
      continue;
    }
    if (file.size > 10 * 1024 * 1024) {
      message.error('图片大小不能超过10M');
      continue;
    }

    files.value.push(file);
    fileUrls.value.push(URL.createObjectURL(file));
  }
};

// 删除文件
const removeFile = (index) => {
  URL.revokeObjectURL(fileUrls.value[index]);
  files.value.splice(index, 1);
  fileUrls.value.splice(index, 1);
};

// 提交表单
const handleSubmit = async () => {
  if (!formData.value.name) {
    message.error('请输入姓名');
    return;
  }
  if (!formData.value.idCard) {
    message.error('请输入身份证号');
    return;
  }
  if (files.value.length === 0) {
    message.error('请上传身份证照片');
    return;
  }

  try {
    // 上传文件并获取 URL
    const uploadedUrls = ref("");
    const form = new FormData();

    files.value.forEach((file) => {
      form.append('files', file); // 注意字段名称与后端一致
    });

    const uploadResponse = await axios.post(`${window.link}/user/file/upload`, form, {
      headers: {
        'access-token': localStorage.getItem('access-token')
      }
    });

    if (uploadResponse.data.code === 200) {
      uploadedUrls.value = uploadResponse.data.data[0]; // 假设后端返回的是数组
    } else {
      message.error(uploadResponse.data.message || '图片上传失败');
      return;
    }

    // 提交认证信息
    const response = await axios.post(
        `${window.link}/user/info/approve`,
        {
          name: formData.value.name,
          idCardNum: formData.value.idCard,
          idCardFile: uploadedUrls.value
        },
        {
          headers: {
            'access-token': localStorage.getItem('access-token'),
            'content-type':'application/JSON'
          }
        }
    );

    if (response.data.code === 200) {
      message.success('提交成功,请重新登录');
      setTimeout(()=>{
        sessionStorage.clear();
        localStorage.clear();
        router.push("/login/loginByAccount")
      },500)
    } else {
      message.error(response.data.message || '提交失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    message.error('提交失败：' + error.message);
  }
};
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <div class="w-[1400px] mx-auto py-8 px-4">
      <div class="bg-white rounded-lg shadow-sm p-6">
        <div class="text-xl font-medium py-6">认证管理</div>
        <div class="bg-white rounded-lg p-12 mb-8 min-h-[calc(1024px-200px)]">
          <div class="max-w-2xl">
            <div class="mb-6">
              <div class="flex items-center mb-2">
                <span class="text-orange-500 mr-1">*</span>
                <span>姓名：</span>
              </div>
              <a-input v-model:value="formData.name" placeholder="请输入姓名" class="!rounded-button" />
            </div>
            <div class="mb-6">
              <div class="flex items-center mb-2">
                <span class="text-orange-500 mr-1">*</span>
                <span>身份证号：</span>
              </div>
              <a-input v-model:value="formData.idCard" placeholder="请输入18位身份证号码" class="!rounded-button" />
            </div>
            <div class="mb-6">
              <div class="mb-2">上传身份证：</div>
              <input
                  type="file"
                  accept="image/jpeg,image/png,image/gif"
                  multiple
                  class="hidden"
                  ref="fileInput"
                  @change="handleImageUpload"
              />
              <div
                  class="border border-dashed border-gray-300 rounded-lg p-6 text-center cursor-pointer hover:border-orange-500 transition-colors"
                  @click="$refs.fileInput.click()"
              >
                <div v-if="files.length === 0">
                  <div class="text-gray-400 mb-2">
                    <i class="fas fa-image text-3xl"></i>
                  </div>
                  <div class="text-gray-500">选择电脑图片上传</div>
                </div>
                <div v-else class="grid grid-cols-2 gap-4">
                  <div v-for="(url, index) in fileUrls" :key="index" class="relative">
                    <img :src="url" class="w-full h-40 object-cover rounded" />
                    <div
                        class="absolute top-2 right-2 bg-red-500 text-white rounded-full w-6 h-6 flex items-center justify-center cursor-pointer"
                        @click.stop="removeFile(index)"
                    >
                      ×
                    </div>
                  </div>
                </div>
              </div>
              <div class="text-gray-400 mt-2 text-sm">
                悬浮您上传清晰、真实的身份证正面照片及手持身份证照片（最多上传2张，每张最大10M）
              </div>
              <div class="text-gray-400 text-sm">仅支持.jpg .jpeg .png .gif 的图片格式</div>
            </div>
            <a-button
                type="primary"
                class="!rounded-button whitespace-nowrap bg-orange-500 border-orange-500 hover:bg-orange-600 hover:border-orange-600"
                @click="handleSubmit"
            >
              提交
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
